/**
 * 公用js库。
 *
 * @author    Fairyin <fairyin@126.com>
 * @copyright © 2016 www.imcn.vip
 * @license   GPL-3.0
 */

$(document).ready(function(){
    if ("object" !== typeof common) common = {};
    
    common.apiurl = "/api/";
    
    common.ajaxtime = 3000;
    
    common.ajax = function(url, method, param, onSuccess, onFailure, token){
        param._token = $("input[name='_token']").val();
        $.ajax({
            url: url,
            type: method,
            beforeSend: function(xhr){
                xhr.setRequestHeader('X-CSRF-TOKEN', token);
            },
            data: param,
            dataType: "json",
        }).done(function(data){
            onSuccess(data);
        })
        .fail(function(error){
            if (error.readyState === 0 && error.status === 0) {

                return false;
            }
            onFailure(JSON.parse(error.responseText));
        });
    };
    
    common.requestUrl = {};

    $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
        var key = options.url;
        if (typeof(common.requestUrl[key]) === 'undefined') {
            common.requestUrl[key] = jqXHR;
        } else {
            //放弃当前触发的请求
            jqXHR.abort();
            //放弃之前触发的请求
            //common.requestUrl[key].abort(); 
        }
        options.complete = function(jqXHR, textStatus) {
            //限制ajax请求延迟时间
            setTimeout(function(){
                delete common.requestUrl[key];
            }, common.ajaxtime);
        };
    });
});

window.onload = function(){
    document.onkeydown = function(event){
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if (e && e.keyCode === 13) { // enter 键
            if ($(".scopes_login").length > 0) {
                _login.login();
            }
        }
    };
};
